const jsonParse = require('../../lib/jsonParse')
const Header = require('../../lib/getHeader');
const CarMains = require('../../schemas/car').CarMains
const CarWaitReadys = require('../../schemas/car').CarWaitReadys
const CarReadys = require('../../schemas/car').CarReadys
const CarHires = require('../../schemas/car').CarHires
const CarReturns = require('../../schemas/car').CarReturns

const SysDictValueList = require('../../schemas/dict').SysDictValueList

const ImgServeIp = require('../../config/keys').imgServeIp

const CarStation = require('../../schemas/stations').CarStations

const {
    ObjectId
} = require('mongodb')

const moment = require('moment');

module.exports = {
    /**
     * 获取车辆列表--所有
     */
    async getCarList(req, res) {
        module.exports.queryCarList(req, res, {})
    },
    /**
     * 获取车辆列表--整备中
     */
    async getPackCar(req, res) {
        module.exports.queryCarList(req, res, {
            carStatus: 4
        })
    },
    /**
     * 获取车辆列表--已整备
     */
    async getReadlyCar(req, res) {
        module.exports.queryCarList(req, res, {
            carStatus: 1
        })
    },
    /**
     * 获取车辆列表--已出租
     */
    async getHireCar(req, res) {
        module.exports.queryCarList(req, res, {
            carStatus: 2
        })
    },
    /**
     * 获取车辆列表函数
     */
    async queryCarList(req, res, obj) {
        let statusList = await SysDictValueList.find({
            dictType: 'dict_car'
        })
        let lockedList = await SysDictValueList.find({
            dictType: 'car_use_status'
        })
        let total = await CarMains.find(obj).count()
        let {
            pageSize,
            pageNum,
            carNumber
        } = req.body;

        let data = {
            ...obj
        }
        if (carNumber) {
            data.carNumber = carNumber
        }
        CarMains.find(data).skip(pageSize * (pageNum - 1)).limit(pageSize).populate('stationId', {stationName: 1}, CarStation).then(async list => {
            const temp = JSON.parse(JSON.stringify(list))
            temp.forEach(e => {
                e.files = {
                    doMain: ImgServeIp,
                    fileUrl: e.carUrl,
                }
                let statusObj = statusList.find(o => o.dictValue == e.carStatus)
                e.carStatusName = statusObj ? statusObj.dictLabel : ''
                let lockedObj = lockedList.find(o => o.dictValue == e.locked)
                e.lockedName = lockedObj ? lockedObj.dictLabel : ''
            })
            setTimeout(() => {
                jsonParse.sendResult(res, 200, {
                    total,
                    records: temp
                }, '查询成功')
            }, 300)
        })
    },

    /**
     * 新增车辆
     */
    async createCar(req, res) {
        const newCarMains = new CarMains({
            ...req.body,
            locked: 1, // 1锁定，2正常
            carStatus: 3
        })
        newCarMains.save().then(car => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * 更新车辆信息
     */
    async updateCar(req, res) {
        await CarMains.findByIdAndUpdate({
            _id: new ObjectId(req.body._id)
        }, {
            $set: {
                ...req.body
            }
        }).then(car => {
            jsonParse.sendResult(res, 200)
        })

    },

    /**
     * 车辆锁定--解锁
     */
    async lockedCar(req, res) {
        const userName = await Header.getUser(req)
        const list = await CarMains.find({
            $and: [{
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                carStatus: {
                    $eq: 2
                }
            }]
        })
        if (list && list.length) {
            jsonParse.sendResult(res, -201, '已出租车辆不允许锁定')
            return false
        }
        CarMains.updateMany({
            carNumber: {
                $in: req.body.carList
            }
        }, {
            $set: {
                locked: req.body.locked,
                handleBy: userName
            }
        }).then(car => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * 整备车辆---待整备
     */
    async handlePackCar(req, res) {
        const userName = await Header.getUser(req)
        const list = await CarMains.find({
            $and: [{
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                carStatus: {
                    $ne: 3
                }
            }]
        })
        if (list && list.length) {
            jsonParse.sendResult(res, -201, '存在不是待整备的车辆')
            return false
        }
        CarMains.updateMany({
            carNumber: {
                $in: req.body.carList
            }
        }, {
            $set: {
                carStatus: 4,
                handleBy: userName
            }
        }).then(() => {
            CarMains.find({
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                _id: 0,
                updateTime: 0,
                createTime: 0,
            }).then(async carList => {
                CarWaitReadys.insertMany(carList).then(() => {
                    jsonParse.sendResult(res, 200)
                })
            })
        })
    },

    /**
     * 整备车辆---完成整备
     */
    async completePackCar(req, res) {
        const userName = await Header.getUser(req)
        const list = await CarMains.find({
            $and: [{
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                carStatus: {
                    $ne: 4
                }
            }]
        })
        if (list && list.length) {
            jsonParse.sendResult(res, -201, '存在不是整备中的车辆')
            return false
        }
        CarMains.updateMany({
            carNumber: {
                $in: req.body.carList
            }
        }, {
            $set: {
                carStatus: 1,
                handleBy: userName
            }
        }).then(() => {
            CarMains.find({
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                _id: 0,
                updateTime: 0,
                createTime: 0,
            }).then(async carList => {
                CarReadys.insertMany(carList).then(() => {
                    jsonParse.sendResult(res, 200)
                })
            })
        })
    },
    /**
     * 整备车辆---出租
     */
    async hirePackCar(req, res) {
        const userName = await Header.getUser(req)
        if (!req.body.carList || !req.body.carList.length) {
            jsonParse.sendResult(res, -2006)
            return
        }
        const list = await CarMains.find({
            $and: [{
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                $or: [{
                    carStatus: {
                        $ne: '1'
                    }
                }, {
                    locked: {
                        $eq: '1'
                    }
                }]
            }]
        })
        if (list && list.length) {
            jsonParse.sendResult(res, -201, '存在不是待出租或锁定的车辆，联系管理员解锁!')
            return false
        }
        CarMains.updateMany({
            carNumber: {
                $in: req.body.carList
            }
        }, {
            $set: {
                carStatus: 2,
                handleBy: userName,
                ...req.body
            }
        }).then(() => {
            CarMains.find({
                carNumber: {
                    $in: req.body.carList
                }
            }, {
                _id: 0,
                updateTime: 0,
                createTime: 0,
                returnTime: 0
            }).then(async carList => {
                CarHires.insertMany(carList).then(() => {
                    jsonParse.sendResult(res, 200)
                })
            })
        })
    },
    /**
     * 整备车辆---还车
     */
    async returnCar(req, res) {
        const userName = await Header.getUser(req)
        const list = await CarMains.find({
            $and: [{
                carNumber: req.body.carObj.carNumber
            }, {
                carStatus: {
                    $eq: 4
                },
                locked: {
                    $ne: 1
                }
            }]
        })
        if (list && list.length) {
            jsonParse.sendResult(res, -201, '存在不是整备完成或锁定的车辆')
            return false
        }
        CarMains.updateMany({
            carNumber: req.body.carObj.carNumber
        }, {
            $set: {
                carStatus: 3,
                handleBy: userName,
                returnTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                ...req.body
            }
        }).then(() => {
            CarMains.find({
                carNumber: req.body.carObj.carNumber
            }, {
                _id: 0,
                updateTime: 0,
                createTime: 0,
            }).then(async carList => {
                CarReturns.insertMany(carList).then(() => {
                    jsonParse.sendResult(res, 200)
                })
            })
        })
    }
}